<template>
  <div class="page-container">
    <div class="top-section">
      <h1 class="title">大屏展示</h1>
      <button id="fullscreenBtn">全屏</button>
    </div>


    <div class="content">
      <div class="data-display">
        <el-table :data="tableData" style="width: 100%;" show-header="false">
          <el-table-column>
            <template slot-scope="scope">
              <p><strong>实有人口:</strong> {{ scope.row.populationCount }}</p>
              <p><strong>实有房屋:</strong> {{ scope.row.buildingCount }}</p>
              <p><strong>实有单位:</strong> {{ scope.row.buildingCount }}</p>
              <p><strong>实有车辆:</strong> {{ scope.row.carCount }}</p>
              <p><strong>实有设备:</strong> {{ scope.row.equipmentCount }}</p>
            </template>
          </el-table-column>
        </el-table>
        <div ref="chart2" class="chart" style="height: 400px;"></div>
        <div class="chart-wrap">
          <div id="chart12" class="chart"></div>
        </div>
      </div>

      <div class="charts">
        <div ref="chart" class="chart" style="height: 350px;"></div>
        <div ref="chart1" class="chart" style="height: 350px;"></div>
        <div class="card-container" style="height: 300px; width: 400px">
          <div v-for="(item, index) in arr" :key="index" class="card-wrapper">
              <div class="card-header">


                  <img :src="item.warnPersonImage" alt="">
<!--                  <span style="align-items: center ;justify-content: center; height: 50px;place-content: center">99%</span>-->
                  <img :src="item.subjectImage" alt="">




              </div>
          </div>
      </div>
      </div>
      <div ref="gaode_Map" id="gaode_Map" class="map"></div>


  </div>
  </div>

</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import RadarChart from '@/components/RadarChart.vue';
const echarts = require('echarts');
// 引入 ECharts 主模块


import {map} from "core-js/internals/array-iteration";
import {
  findAllCount, findAllOutLine,
  findHouseTypeCount, findLastWarn,
  findPersonType,
  findPlotLists,
  findPopulationCount
} from "@/api/community/plot";
import {findVehicledeploymentCount} from "@/api/community/division"; //引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "a97ace3a685329a45d528a00b082b51d",
};
export default {
  name: 'Index',
  components  : {
    RadarChart
  },
  props: [],
  data() {
    return {
      chart: null,
      data1: [60, 70, 50, 80, 66, 77],
      data2: [86, 83, 82, 91, 90, 87],
      chartData: {
        labels: ['指标1', '指标2', '指标3', '指标4', '指标5'],
        datasets: [
          {
            label: '数据集1',
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            pointBackgroundColor: 'rgba(255, 99, 132, 1)',
            data: [20, 30, 40, 50, 60] // 替换为你自己的数据
          }
        ]
      },
      metrics: {
        perceptual_discovery: 0,
        perception_leaves: 0,
        stranded_discovery: 0,
        first_discovered: 0
      },
      chart3: null,
      chartOption: {
        // 初始的图表配置，可以留空或设置一些基本的样式
        title: {
          text: '加载中...'
        }
      },
      tableData:[],
      tableData1:[],
      plotData:{},
      peosonData:[],
      loading: false,
      // visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      arr:[],
      rules: {},
      input: "",
      input1: "",
      longitude: "",
      latitude: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
      domicileCount:0,
      foreignCount:0,
      abroadCount:0,
      temporaryCount:0,
      barData: [],
      // lng: 0, // 初始化经度
      // lat: 0, // 初始化纬度
    };
  },

  computed: {},
  watch: {},
  created() {


  },
  mounted() {
    this.getData();
    this.initMap();
    this.getData1();
    this.initCharts();
    this.getData2();
    this.getData3();
    this.getPlotData();
    this.fetchData();
    this.createChartHandler();
    this.getWarn();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    getWarn(){
      findLastWarn().then(res=>{
        this.arr=res.data
        this.total=res.data.total
        console.log(res.data);
      })
    },

    createChartHandler() {
      this.chart = echarts.init(document.getElementById('chart12'));
      this.chart.setOption(this.getChartOption(this.data1, this.data2));
      window.addEventListener('resize', this.resizeChart);
    },
    resizeChart() {
      this.chart.resize();
    },
    getChartOption(data1, data2) {
      return {
        tooltip: {},
        radar: {
          indicator: [
            { name: '感知发现', max: 100 },
            { name: '感知离开', max: 203 },
            { name: '滞留发现', max: 200 },
            { name: '首次来访', max: 56 },
          ]
        },
        series: [
          {
            name: '上月指数',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 4,
            areaStyle: {
              color: '#06C88C',
            },
            itemStyle: {
              color: '#06C88C',
            },
            lineStyle: {
              type: 'dashed',
              color: '#06C88C',
              width: 2,
            },
            data: [data1], // 确保 data1 直接传递
          },
          {
            name: '当月指数',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 4,
            itemStyle: {
              color: '#63BCFF',
            },
            areaStyle: {
              color: '#63BCFF',
            },
            lineStyle: {
              color: '#63BCFF',
              width: 2,
              type: 'dashed',
            },
            data: [data2], // 确保 data2 直接传递
          },
        ],
      };
    },

    fetchData() {
      findVehicledeploymentCount().then(res => {
        // 确保响应数据结构正确
        this.chartData.datasets[0].data = res.data; // 和原数据相结合，形成正确的数据格式
        this.total = res.total; // 如果总数需要使用
        console.log(res.data);
      });
    },




  getData2() {
      // 假设findPopulationCount()方法是用来获取数据的异步请求
      findHouseTypeCount().then(res => {
        this.barData = [
          { value: res.data.selfoccupiedCount, name: '自住房' },
          { value: res.data.ldleCount, name: '闲置房' },
          { value: res.data.leaseCount, name: '租赁房' },
          { value: res.data.otherCount, name: '其它' }
        ];
        this.initBarChart();
      });
    },
    getData3() {
      // 假设findPopulationCount()方法是用来获取数据的异步请求
      findPersonType().then(res => {
        this.peosonData = [
          { value: res.data.longTermUnappear, name: '长期未出现' },
          { value: res.data.inward, name: '外来活动频繁人员' },
          { value: res.data.visit, name: '来访重点关注人员' },
          { value: res.data.longTermAppear, name: '长期住户' }
        ];
        this.initBarChart2();
      });
    },
    initBarChart() {
      let myChart = echarts.init(this.$refs.chart1);

      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: this.barData.map(item => item.name)
        },
        series: [
          {
            type: 'bar',
            data: this.barData.map(item => item.value),
            label: {
              show: true,
              position: 'right'
            }
          }
        ]
      });
    },
    initBarChart2() {
      let myChart = echarts.init(this.$refs.chart2);

      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: this.peosonData.map(item => item.name)
        },
        series: [
          {
            type: 'bar',
            data: this.peosonData.map(item => item.value),
            label: {
              show: true,
              position: 'right'
            }
          }
        ]
      });
    },
    initCharts() {
      let myChart = echarts.init(this.$refs.chart);

      myChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.tableData1.map(item => item.name)
        },
        series: [
          {
            name: '销量',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.tableData1,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    },
    getData(){
      findAllCount().then(res=>{
        this.tableData=res.data
        this.total=res.data.total
        console.log(res.data);
      })
    },
    getData1() {
      findPopulationCount().then(res => {
        this.tableData1 = [
          { value: res.data.domicileCount, name: '户籍人员' },
          { value: res.data.foreignCount, name: '外来人员' },
          { value: res.data.abroadCount, name: '境外人员' },
          { value: res.data.temporaryCount, name: '临时人员' }
        ];
        console.log(this.tableData1);
        this.initCharts(); // 在数据获取成功后初始化图表
      });
    },



    initMap() {
      let centerLen = [116.397471,39.908536];
      AMapLoader.load({
        key: "085f7d1a48acc9b9611b99096b0a0589", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder", 'AMap.ToolBar',
          'AMap.Scale'],
      })
        .then((AMap) => {
          this.Amap = AMap;
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,
            mapStyle: 'amap://styles/white' // 使用主题
          });

          let allPolygonsPromises = [];

          // 假设你有一个函数，用于获取所有多边形的坐标
          findAllOutLine().then(res => {

            let allOutlines=res.data
            console.log(allOutlines)
            allOutlines.forEach(outline => {

              let coordinatesArray = outline.split(',');
              let pointsCollection = [];

              for (let i = 0; i < coordinatesArray.length; i += 2) {
                pointsCollection.push([parseFloat(coordinatesArray[i]), parseFloat(coordinatesArray[i + 1])]);
              }

              // 创建多边形
              let polygon = new AMap.Polygon({
                map: this.map,
                path: pointsCollection,
                strokeColor: "#FF33FF", // 线颜色
                strokeWeight: 6, // 线宽
                strokeOpacity: 0.2, // 线透明度
                fillColor: '#1791fc', // 填充色
                fillOpacity: 0.35, // 填充透明度
                zIndex: 50,
              });

              // 你可以选择保存已创建的多边形（可选）
              allPolygonsPromises.push(polygon);
            });

            // 可选：处理绘制完成的逻辑，例如寄存多边形信息、更新 UI 等
            console.log("所有多边形已绘制", allPolygonsPromises);
          });



          this.map.addControl(new AMap.Scale()); // 比例尺
          this.map.addControl(new AMap.ToolBar()); // 工具条


          this.setMarker(centerLen)
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
          // 添加全屏按钮点击事件
          document.getElementById('fullscreenBtn').addEventListener('click', function () {
            if (this.map.getContainer().requestFullscreen) {
              this.map.getContainer().requestFullscreen();
            } else if (this.map.getContainer().mozRequestFullScreen) { /* Firefox */
              this.map.getContainer().mozRequestFullScreen();
            } else if (this.map.getContainer().webkitRequestFullscreen) { /* Chrome, Safari & Opera */
              this.map.getContainer().webkitRequestFullscreen();
            } else if (this.map.getContainer().msRequestFullscreen) { /* IE/Edge */
              this.map.getContainer().msRequestFullscreen();
            }
          }.bind(this)); // 使用bind确保this指向正确
        })


        .catch((e) => {
        });

    },

    searchMapByCoordinates() {
      let lng = parseFloat(this.longitude); // 将经度从字符串转换为数值类型
      let lat = parseFloat(this.latitude); // 将纬度从字符串转换为数值类型

      if (isNaN(lng) || isNaN(lat)) {
        alert('请输入有效的经度和纬度');
        return;
      }
      // 根据经度和纬度设置地图中心点
      let map = new AMap.Map("gaode_Map", {
        resizeEnable: true,
        center: [lng, lat],
        zoom: 13
      });

      // 在地图上添加标记点
      // let marker = new AMap.Marker({
      //   position: [lng, lat],
      //   map: map
      // });
      // 创建圆形
      let circle = new this.Amap.Circle({
        center: [lng, lat], // 设置圆心位置
        radius: 1000, // 设置半径，单位为米
        strokeColor: "#FF33FF", // 线颜色
        strokeOpacity: 0.3, // 线透明度
        strokeWeight: 3, // 线宽
        fillColor: "#1791fc", // 填充颜色
        fillOpacity: 0.2, // 填充透明度
      });

      // 将圆形添加到地图上
      circle.setMap(map);
      // 模拟社区数据，实际情况请根据您的数据源获取真实社区数据
      let communities = [
        {name: "Community A", lng: lng + 0.005, lat: lat + 0.005},
        {name: "Community B", lng: lng - 0.003, lat: lat - 0.005},
        {name: "Community C", lng: lng + 0.002, lat: lat - 0.002}
        // Add more communities as needed
      ];

      // 统计圆形区域内的社区总数
      let communityCount = communities.filter(community => {
        return this.calculateDistance(community.lng, community.lat, lng, lat) <= radius;
      }).length;

      console.log("Total community count in the circle: ", communityCount);
      alert("此区域内社区数量为：" + communityCount);
    },


// 计算两点之间的距离
    calculateDistance(lng1, lat1, lng2, lat2) {
      let radian = Math.PI / 180;
      let radius = 6378137; // 地球半径，单位为米
      let dLat = (lat2 - lat1) * radian;
      let dLng = (lng2 - lng1) * radian;
      let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * radian) * Math.cos(lat2 * radian) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
      let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return radius * c;
    },

    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //选中查询出的记录
    selectSite(e) {
      if (e.poi.location) {
        this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            that.province = result.regeocode.addressComponent.province;
            that.city = result.regeocode.addressComponent.city;
            //自己想要赋的值，根据自己的做修改
            that.$set(that.form, "province", that.province);
            that.$set(that.form, "city", that.city);
            that.$set(that.form, "address", e.poi.name);
            that.$set(
              that.form,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度，经度
          } else {
          }
        });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },
    getPlotData(){
      findPlotLists().then(res=>{
        this.plotData=res.data
        this.addMarkers()
        this.total=res.data.total
        console.log(this.tableData1);
      })
    },
    addMarkers() {
      this.plotData.forEach((tableData, index) => {
        let marker = new AMap.Marker({
          position: [tableData.longitude, tableData.latitude],
        });
        marker.setMap(this.map);
        this.markers.push(marker);
      });
    },
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      alert(this.lnglat);
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
        } else {
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker(lnglat) {
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // setMarkers(lnglat) {
    //   // 创建新的标记对象
    //   let marker = new AMap.Marker({
    //     position: lnglat,
    //   });
    //   marker.setMap(this.map);
    //   this.markeres.push(marker); // 将新创建的标记对象推入数组
    // },
    // 删除之前后的标记点
    removeAllMarkers() {
      this.markers.forEach(marker => {
        marker.setMap(null);
      });
      this.markers = [];
    }

  },
};
</script>


<style lang="scss">
.chart-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px; /* 调整内边距 */
  background-color: #f8f9fa; /* 背景颜色 */
  border-radius: 10px; /* 圆角 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.chart {
  width: 100%;
  height: 400px; /* 根据需要调整高度 */
}
.page-container {
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.top-section {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 10px 20px;
  border-bottom: 1px solid #eaeaea;
}

.title {
  font-size: 24px;
  color: #333;
}

.content {
  display: flex; /* 使用 flex 布局 */
  justify-content: space-between; /* 均匀分布子元素 */
  align-items: flex-start; /* 顶部对齐 */
  height: 1500px; /* 设置容器高度 */
}

.data-display {
  width: 40%; /* 数据区宽度 */
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-right: 20px; /* 添加右边距 */
}

.charts {
  display: flex;
  flex-direction: column;
  gap: 10px; /* 图表之间间隔 */
  width: 30%; /* 图表区宽度 */
  margin-right: 20px; /* 添加右边距 */
}

.chart {
  width: 100%;
  background-color: #f0f0f0; /* 图表背景颜色 */
  border-radius: 8px;
  padding: 10px;
  height: 300px; /* 设置图表高度 */
}

.map {
  width: 90%; /* 地图宽度 */
  height: 1030px; /* 增加地图的高度 */
  border-radius: 10px;
  overflow: hidden; /* 隐藏溢出的内容 */
}

.el-button {
  background-color: #007bff;
  border: none;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  transition: background-color 0.3s, transform 0.3s;
}

.el-button:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
}

#fullscreenBtn {
  background-color: #28a745;
  border: none;
  color: white;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s, transform 0.3s;
}

#fullscreenBtn:hover {
  background-color: #218838;
  transform: scale(1.05);
}
</style>



